package com.example.teach.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.teach.entity.Result;
import com.example.teach.entity.User;
import com.example.teach.service.UserService;
import com.example.teach.utils.JwtUtil;
import jakarta.annotation.Resource;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.encrypt.RsaAlgorithm;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.lang.invoke.LambdaConversionException;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @PutMapping("/update")
    public Result update(@RequestBody User user) {
        userService.updateById(user);
        return Result.success();
    }
//    @GetMapping("/testJwt")
//    public Result testJwt() {
//        // 获取当前认证信息
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//
//        if (authentication == null) {
//            return Result.error("未获取到认证信息");
//        }
//
//        // 从认证信息中获取用户名
//        String username = authentication.getName();
//
//        // 也可以通过JwtUtil直接从令牌中解析信息（如果需要的话）
//        // String token = ...; // 从请求头中获取token
//        // String usernameFromToken = JwtUtil.getUsernameFromToken(token);
//        // Integer userTypeFromToken = JwtUtil.getUserTypeFromToken(token);
//
//        return Result.success("JWT验证成功", "当前登录用户: " + username);
//    }

    @GetMapping("/id")
    public Result getId(@RequestParam Integer userId){
        return userService.selectId(userId);
    }

    @GetMapping("/selectById")
    public Result selectById(@RequestParam("id") Integer id) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserId, id);
        User user = userService.getOne(queryWrapper);
        return Result.success(user);
    }

    @GetMapping("/selectAll")
    public Result selectAll() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        List<User> users = userService.list(queryWrapper);
        return Result.success("查找成功",users);
    }

    @PostMapping("/register")
    public Result register(@RequestBody User user) {

        if(StrUtil.isEmpty(user.getUserName()) || StrUtil.isEmpty(user.getPassWord())){
            return Result.error(400,"用户名或密码不能为空");
        }

        if(userService.selectOne(user.getUserName())){
            return Result.error("用户名已存在");
        }
        userService.add(user);
        return Result.success();
    }

    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        if(StrUtil.isEmpty(user.getUserName()) || StrUtil.isEmpty(user.getPassWord())){
            return Result.error("用户名或密码不能为空");
        }
        User u = userService.login(user);
        if(u != null){
            String token = JwtUtil.generateToken(u.getUserId(),u.getUserName(),u.getUserType());
            return Result.success("登陆成功",token);
        }else{
            return Result.error("用户名或密码错误");
        }
    }

    @GetMapping("/page")
    public Result page(@RequestParam(value="pageNum",defaultValue = "1") Integer pageNum,
                       @RequestParam(value="pageSize",defaultValue = "10") Integer pageSize,
                       @RequestParam(value="userId", defaultValue = "") Integer userId,
                       @RequestParam(value="userName",defaultValue = "") String userName){
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if(userId != null){
            queryWrapper.eq(User::getUserId,userId);
        }
        if(StrUtil.isNotEmpty(userName)){
            queryWrapper.like(User::getUserName,userName);
        }
        //Page<User> page = userService.page(new Page<>(pageNum,pageSize), queryWrapper)
        return Result.success(userService.page(new Page<>(pageNum,pageSize), queryWrapper));
    }

}
